package com.muatocroi.tornado;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.SocketAddress;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.util.ArrayList;

import android.media.AudioFormat;
import android.media.AudioRecord;
import android.media.MediaRecorder;
import android.os.Bundle;
import android.app.Activity;
import android.app.ActivityManager;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Toast;
import android.widget.ToggleButton;
import android.util.Log;

public class SendAudioActivity extends ActivityMCAbstractClass implements OnClickListener, Runnable {

    static final int AUDIO_PORT = 2048;
    static final int SAMPLE_RATE = 8000;
    static final int SAMPLE_INTERVAL = 20; // milliseconds
    static final int SAMPLE_SIZE = 2; // bytes per sample
    static final int BUF_SIZE = SAMPLE_INTERVAL*SAMPLE_INTERVAL*SAMPLE_SIZE*2;
    static final String LOG_TAG = "AudioUdpStream";
    
    public boolean stopSend = true;
    
    private static ServerSocket listener = null;
    SignalSender sender = null;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_send_audio);
		
		ToggleButton tgBtnStartAudio = (ToggleButton)findViewById(R.id.tgBtnStartAudio);
		tgBtnStartAudio.setOnClickListener(this);
		
		sender = SignalSender.getSender();
		if(!sender.isSending())
		{
			sender.BeginSend();
		}
		
	}

	@Override
	public void onClick(View v) {
		int id = v.getId();
		switch(id)
		{
			case R.id.tgBtnStartAudio:
				sendMicAudio();
				break;
		}
	}
	
	public void sendMicAudio()
	{
		if (stopSend)
		{
			Thread thrSendFile = new Thread(this);
			thrSendFile.start();
			stopSend = false;
		}
		else
		{
			stopSend = true;
		}
	}

	@Override
	public void run() {
		 Log.e(LOG_TAG, "start SendMicAudio thread, thread id: "+ Thread.currentThread().getId());
		 
		 int bytes_read = 0;
		 int bytes_count = 0;
		 byte[] buf = new byte[BUF_SIZE];
		 
		 AudioRecord audio_recorder = new AudioRecord(MediaRecorder.AudioSource.DEFAULT, SAMPLE_RATE,AudioFormat.CHANNEL_CONFIGURATION_MONO,AudioFormat.ENCODING_PCM_16BIT, AudioRecord.getMinBufferSize(SAMPLE_RATE,AudioFormat.CHANNEL_CONFIGURATION_MONO,AudioFormat.ENCODING_PCM_16BIT) * 10);
		 
		 try
            {
			 	ArrayList<InetAddress> broadcasts = AddressLocal.getBroadcasts();
                SocketAddress broadcast = new InetSocketAddress(broadcasts.get(0), AUDIO_PORT);
                DatagramSocket sock = new DatagramSocket();
                //while(true)
                audio_recorder.startRecording();
                while(!stopSend)
                {
                    bytes_read = audio_recorder.read(buf, 0, BUF_SIZE);
                    DatagramPacket pack = new DatagramPacket(buf, bytes_read, broadcast);
                    sock.send(pack);
                    bytes_count += bytes_read;
                    Log.d(LOG_TAG, "bytes_count : " + bytes_count);
                    Thread.sleep(SAMPLE_INTERVAL, 0);
                }
                audio_recorder.stop();
                audio_recorder.release();
            }
            catch (InterruptedException ie)
            {
                Log.e(LOG_TAG, "InterruptedException");
            }
		 	catch (SocketException se)
            {
                Log.e(LOG_TAG, "SocketException");
            }
		 	catch (UnknownHostException uhe)
            {
                Log.e(LOG_TAG, "UnknownHostException");
            }
		 	catch (IOException ie)
            {
                Log.e(LOG_TAG, "IOException");
            }
	}

}
